package com.example.android_app;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.DigitalClock;
import android.widget.Gallery;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android_app.network.mqtt.opp.MQTTConnection;
import com.example.android_app.network.opp.ExecuteNetworkOpp;
import com.example.android_app.network.services.consmp.AddToHandRequestService;
import com.example.android_app.network.services.consmp.DropCardRequestService;
import com.example.android_app.network.services.consmp.SimpleTextService;
import com.example.android_app.network.services.consmp.StartGameRequestService;
import com.example.android_app.struc.Card;
import com.example.android_app.struc.Update;
import com.example.android_app.widget.GalleryAdapterAll;
import com.example.android_app.widget.GalleryAdapterHand;
import com.ibm.mqtt.MqttException;
import com.pervasive.project.unified.data.constants.Constants;
import com.pervasive.project.unified.data.model.dto.CardInfoContainer;
import com.pervasive.project.unified.data.model.request.AddToHandRequest;
import com.pervasive.project.unified.data.model.request.DropCardRequest;
import com.pervasive.project.unified.data.model.request.StartGameRequest;
import com.pervasive.project.unified.data.model.response.StartGameResponse;

public class GameActivity extends Activity {
	
	
	private static final int CAMERA_PIC_REQUEST = 2500;
	private Gallery gallery_hand, gallery_open;
	private RatingBar ratingBar;
	private int NO_STARS=0;
	private int  current_pick= 0;
	private List<Card> hand, red, blue, green, yellow;
	private GalleryAdapterAll galImageAdapter_all, galImageAdapter_red, galImageAdapter_blue, galImageAdapter_green, galImageAdapter_yellow;
	private GalleryAdapterHand galImageAdapter_hand;
	private Button red_button, blue_button, green_button, yellow_button;
	private TextView timerView, scoreView;
	private Timer timer;
	private String userName;
	private static int minute;
	private static int sec;
	private static boolean timerEnd;
	
	private HashMap<Constants.cardId, Card> openCardMap, handCardMap;
	private int totalScore;
	
	private static final int scoreConstant = 10;
	
	private DefaultHttpClient httpclient;
	
	private GameUpdate gameUpdateThread;
	
	private StartGameResponse gameResponse;

	//@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_game);
		// TODO: Get the User credentials
		userName = this.getIntent().getExtras().getString("username");
		
		httpclient = new DefaultHttpClient();
		
		ExecuteNetworkOpp networkOppThrd = (new ExecuteNetworkOpp(new StartGameRequestService(httpclient, this, generateStartGameRequest())));
		networkOppThrd.start();
		
		try {
			networkOppThrd.join();
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		// Ends
		
		// MQTT
		try {
			gameUpdateThread = new GameUpdate(this);
			gameUpdateThread.start();
			//Toast.makeText(GameActivity.this, "No Exp",Toast.LENGTH_LONG).show();
		} catch (NotFoundException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			System.out.println(" ======== Exception Occured While Creating GameUpdateThread 1 =========== ");
			//Toast.makeText(GameActivity.this, "Exp 1",Toast.LENGTH_LONG).show();
		} catch (MqttException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			System.out.println(" ======== Exception Occured While Creating GameUpdateThread 2 =========== ");
			//Toast.makeText(GameActivity.this, "Exp 2",Toast.LENGTH_LONG).show();
		} 
		
		// *** DUMMY SERVER CALL ***
		//StartGameResponse gameResponse = com.dummy.server.StartGame.startGame(generateStartGameRequest());
		
		// Initialize data-strucs
		initialize();
		
		// Populate Open Card Itenaries
		populateOpenCardItenary(gameResponse.getRedOpen().iterator());
		populateOpenCardItenary(gameResponse.getBlueOpen().iterator());
		populateOpenCardItenary(gameResponse.getGreenOpen().iterator());
		populateOpenCardItenary(gameResponse.getYellowOpen().iterator());
		
	    // Populate Hand Itenary
		populateHandCardItenary(gameResponse.getRedHand().iterator());
		populateHandCardItenary(gameResponse.getBlueHand().iterator());
		populateHandCardItenary(gameResponse.getGreenHand().iterator());
		populateHandCardItenary(gameResponse.getYellowHand().iterator());
		
		
		// TODO: Obtain the Game Start Request and populate the Screen
		
		//Populating the cards into the lists for each COLOR: 'red','blue', 'green', 'yellow'
		/*getList_red();
		getList_blue();
		getList_green();
		getList_yellow();
		getList_open();
		getList_hand();*/
		
		// Set the Timer
		timer = new Timer();
		timerView = (TextView)findViewById(R.id.timer);
		minute = gameResponse.getMinute();
		sec = gameResponse.getSeconds();
		timerEnd = false;
		
		scoreView = (TextView)findViewById(R.id.score);
		
		setUI();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if(gameUpdateThread != null)
		{
			gameUpdateThread.setValidity(false);
		}
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		
	}
	
	private StartGameRequest generateStartGameRequest()
	{
		return new StartGameRequest(userName);
	}
	
	private void populateOpenCardItenary(Iterator<CardInfoContainer> cardIterator)
	{
		while(cardIterator.hasNext())
		{
			Card card = generateCard(cardIterator.next());
			switch (card.getCardId().getCardType()) 
			{
				case RED:
					red.add(card);
					break;
					
				case BLUE:
					blue.add(card);
					break;
					
				case GREEN:
					green.add(card);
					break;
					
				case YELLOW:
					yellow.add(card);
					break;

				default:
					break;
			}
			
			openCardMap.put(card.getCardId(), card);
		}
	}
	
	public void updateStartGameInfo(StartGameResponse gameResponse)
	{
		this.gameResponse = gameResponse;
	}
	
	private void populateHandCardItenary(Iterator<CardInfoContainer> cardIterator)
	{
		while(cardIterator.hasNext())
		{
			Card card = generateCard(cardIterator.next());
			hand.add(card);
			
			totalScore += card.getScore();
			handCardMap.put(card.getCardId(), card);
		}
	}
	
	private void initialize()
	{
		red = new ArrayList<Card>();
		blue = new ArrayList<Card>();
		green = new ArrayList<Card>();
		yellow = new ArrayList<Card>();
		
		hand = new ArrayList<Card>();
		
		handCardMap = new HashMap<Constants.cardId, Card>();
		openCardMap = new HashMap<Constants.cardId, Card>();
	}
	
	public void setValueonRatingBar(int rating) 
	{
		System.out.println("Current Rating --> "+rating);
		ratingBar = (RatingBar) findViewById(R.id.ratingBar);
		ratingBar.setRating(rating);
	}		 

	private void setUI() {
		gallery_open = (Gallery) findViewById(R.id.gallery_all);
		gallery_hand = (Gallery) findViewById(R.id.gallery_hand);
		//Context context = this;
		/*galImageAdapter_all = new GalleryAdapterAll(this, open, Constants.cardType.ALL);
		gallery_open.setAdapter(galImageAdapter_all);*/

		//RED button
		galImageAdapter_red = new	GalleryAdapterAll(this, red, Constants.cardType.RED);
		red_button = (Button) findViewById(R.id.red_button);
		red_button.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//galImageAdapter_all = getGalleryAdapterAll(all);
				
				gallery_open.setAdapter(galImageAdapter_red);

				if (red.size() > 0) {
					gallery_open.setSelection(0, false);
				}					
			}
		});


		//BLUE button
		galImageAdapter_blue = new	GalleryAdapterAll(this, blue, Constants.cardType.BLUE);
		blue_button = (Button) findViewById(R.id.blue_button);
		blue_button.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//galImageAdapter_all = getGalleryAdapterAll(all);
				
				gallery_open.setAdapter(galImageAdapter_blue);

				if (blue.size() > 0) {
					gallery_open.setSelection(0, false);
				}					
			}
		});

		
		
		//GREEN button
		galImageAdapter_green = new	GalleryAdapterAll(this, green, Constants.cardType.GREEN);
		green_button = (Button) findViewById(R.id.green_button);
		green_button.setOnClickListener(new OnClickListener() {
		public void onClick(View v) {
			// TODO Auto-generated method stub
			//galImageAdapter_all = getGalleryAdapterAll(all);						
			gallery_open.setAdapter(galImageAdapter_green);
			if (green.size() > 0) 
				gallery_open.setSelection(0, false);		
			}
		});
				
		
		//YELLOW button
		galImageAdapter_yellow = new	GalleryAdapterAll(this, yellow, Constants.cardType.YELLOW);
		yellow_button = (Button) findViewById(R.id.yellow_button);
		yellow_button.setOnClickListener(new OnClickListener() {
		public void onClick(View v) {
			// TODO Auto-generated method stub
			//galImageAdapter_all = getGalleryAdapterAll(all);						
			gallery_open.setAdapter(galImageAdapter_yellow);
			if (yellow.size() > 0) 
				gallery_open.setSelection(0, false);		
			}
		});
				
						
		galImageAdapter_hand = new GalleryAdapterHand(this, hand);
		gallery_hand.setAdapter(galImageAdapter_hand);

		
		gallery_open.setOnItemSelectedListener(new 
			OnItemSelectedListener(){
			//@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id){
				/*current_pick = pos;
				NO_STARS = (current_pick+1)%4;
				setValueonRatingBar(NO_STARS);*/
				System.out.println("Selected Position in G --> "+gallery_open.getSelectedItemPosition());
				switch(((GalleryAdapterAll)gallery_open.getAdapter()).getCardType())
				{
					case RED:
						setValueonRatingBar(red.get(gallery_open.getSelectedItemPosition()).getCardStar().getExp());
						break;
						
					case BLUE:
						setValueonRatingBar(blue.get(gallery_open.getSelectedItemPosition()).getCardStar().getExp());
						break;
						
					case GREEN:
						setValueonRatingBar(green.get(gallery_open.getSelectedItemPosition()).getCardStar().getExp());
						break;
						
					case YELLOW:
						setValueonRatingBar(yellow.get(gallery_open.getSelectedItemPosition()).getCardStar().getExp());
						break;
				}
				
			}
			//@Override
			public void onNothingSelected(AdapterView<?> arg0){
		
			}
		});
	
		gallery_open.setOnItemClickListener(new OnItemClickListener(){
			//@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long a){
				if(galImageAdapter_hand.getCount() <= 13)
				{
					NO_STARS=0;
					setValueonRatingBar(NO_STARS);
					Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
					startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
				}else{
					Toast.makeText(GameActivity.this, "Only 13 Cards Allowed In Hand",Toast.LENGTH_LONG).show();
				}
				
				// **** EXPERIMENTAL ****
				//onActivityResult_DUMMY();
			}
		});
		
		gallery_hand.setOnItemClickListener(new HandItemClickListener());
		
		if(!red.isEmpty())
		{
			gallery_open.setAdapter(galImageAdapter_red);

			if (red.size() > 0) {
				gallery_open.setSelection(0, false);
			}					

		}else if(!blue.isEmpty())
		{
			gallery_open.setAdapter(galImageAdapter_blue);

			if (red.size() > 0) {
				gallery_open.setSelection(0, false);
			}					

		}else if(!green.isEmpty())
		{
			gallery_open.setAdapter(galImageAdapter_green);

			if (red.size() > 0) {
				gallery_open.setSelection(0, false);
			}					

		}else if(!yellow.isEmpty())
		{
			gallery_open.setAdapter(galImageAdapter_yellow);

			if (red.size() > 0) {
				gallery_open.setSelection(0, false);
			}					

		}
			
		// Setting the Timer View
		timer.scheduleAtFixedRate(new GameTimerTask(), 0, 1000);
		
		// Setting the initial Score
		scoreView.setText(""+totalScore+"");
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
			Bitmap image = (Bitmap) data.getExtras().get("data");
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			image.compress(CompressFormat.JPEG, 100 /* ignored for PNG */, bos);
			byte[] bitmapdata = bos.toByteArray();
			AddToHandRequest addToHandRequest;
			
			int position = gallery_open.getSelectedItemPosition();
			int count = gallery_open.getCount();

			switch (((GalleryAdapterAll) gallery_open.getAdapter())
					.getCardType()) {
			case RED:
				// *** DUMMY SERVER CALL ***
				red.get(position).setScore(red.get(position).getCardStar().getValue()*scoreConstant);
				addToHandRequest = new AddToHandRequest(red.get(position).getCardId(), userName, bitmapdata, red.get(position).getScore());
				(new ExecuteNetworkOpp(new AddToHandRequestService(httpclient, this, addToHandRequest))).start();
				
				totalScore += red.get(position).getScore();
				handCardMap.put(red.get(position).getCardId(), red.get(position));
				openCardMap.remove(red.get(position).getCardId());
				
				hand.add(red.get(position));
				red.remove(position);

				galImageAdapter_red = new GalleryAdapterAll(this, red,
						Constants.cardType.RED);
				gallery_open.setAdapter(galImageAdapter_red);

				if ((position - 1) > 0) {
					gallery_open.setSelection((position - 1), false);
				} else if (position == 0 && count > 1)
					gallery_open.setSelection((position), false);

				galImageAdapter_hand = new GalleryAdapterHand(this, hand);
				gallery_hand.setAdapter(galImageAdapter_hand);
				break;

			case BLUE:
				// *** DUMMY SERVER CALL ***
				blue.get(position).setScore(blue.get(position).getCardStar().getValue()*scoreConstant);
				addToHandRequest = new AddToHandRequest(blue.get(position).getCardId(), userName, bitmapdata, blue.get(position).getScore());
				(new ExecuteNetworkOpp(new AddToHandRequestService(httpclient, this, addToHandRequest))).start();
				
				totalScore += blue.get(position).getScore();
				handCardMap.put(blue.get(position).getCardId(), blue.get(position));
				openCardMap.remove(blue.get(position).getCardId());
				
				hand.add(blue.get(position));
				blue.remove(position);

				galImageAdapter_blue = new GalleryAdapterAll(this, blue,
						Constants.cardType.BLUE);
				gallery_open.setAdapter(galImageAdapter_blue);

				if ((position - 1) > 0) {
					gallery_open.setSelection((position - 1), false);
				} else if (position == 0 && count > 1)
					gallery_open.setSelection((position), false);

				galImageAdapter_hand = new GalleryAdapterHand(this, hand);
				gallery_hand.setAdapter(galImageAdapter_hand);
				break;

			case GREEN:
				// *** DUMMY SERVER CALL ***
				green.get(position).setScore(green.get(position).getCardStar().getValue()*scoreConstant);
				addToHandRequest = new AddToHandRequest(green.get(position).getCardId(), userName, bitmapdata, green.get(position).getScore());
				(new ExecuteNetworkOpp(new AddToHandRequestService(httpclient, this, addToHandRequest))).start();
				
				totalScore += green.get(position).getScore();
				handCardMap.put(green.get(position).getCardId(), green.get(position));
				openCardMap.remove(green.get(position).getCardId());
				
				hand.add(green.get(position));
				green.remove(position);

				galImageAdapter_green = new GalleryAdapterAll(this, green,
						Constants.cardType.GREEN);
				gallery_open.setAdapter(galImageAdapter_green);

				if ((position - 1) > 0) {
					gallery_open.setSelection((position - 1), false);
				} else if (position == 0 && count > 1)
					gallery_open.setSelection((position), false);

				galImageAdapter_hand = new GalleryAdapterHand(this, hand);
				gallery_hand.setAdapter(galImageAdapter_hand);
				break;

			case YELLOW:
				// *** DUMMY SERVER CALL ***
				yellow.get(position).setScore(yellow.get(position).getCardStar().getValue()*scoreConstant);
				addToHandRequest = new AddToHandRequest(yellow.get(position).getCardId(), userName, bitmapdata, yellow.get(position).getScore());
				(new ExecuteNetworkOpp(new AddToHandRequestService(httpclient, this, addToHandRequest))).start();
				
				totalScore += yellow.get(position).getScore();
				handCardMap.put(yellow.get(position).getCardId(), yellow.get(position));
				openCardMap.remove(yellow.get(position).getCardId());
				
				hand.add(yellow.get(position));
				yellow.remove(position);

				galImageAdapter_yellow = new GalleryAdapterAll(this, yellow,
						Constants.cardType.YELLOW);
				gallery_open.setAdapter(galImageAdapter_yellow);

				if ((position - 1) > 0) {
					gallery_open.setSelection((position - 1), false);
				} else if (position == 0 && count > 1)
					gallery_open.setSelection((position), false);

				galImageAdapter_hand = new GalleryAdapterHand(this, hand);
				gallery_hand.setAdapter(galImageAdapter_hand);
				break;
			}
			
			// Setting the updated Score
			scoreView.setText(""+totalScore+"");
		}
	}
	
	// DUMMY EXPERIMENTAL
	public void onActivityResult_DUMMY()
	{
		int position = gallery_open.getSelectedItemPosition();
		int count = gallery_open.getCount();
		AddToHandRequest addToHandRequest;
		
		//byte[] bitmapdata = new byte[10];
		Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.hand1);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		image.compress(CompressFormat.JPEG, 0 /* ignored for PNG */, bos);
		byte[] bitmapdata = bos.toByteArray();
		
		switch(((GalleryAdapterAll)gallery_open.getAdapter()).getCardType())
		{
			case RED:
				red.get(position).setScore(red.get(position).getCardStar().getValue()*scoreConstant);
				addToHandRequest = new AddToHandRequest(red.get(position).getCardId(), userName, bitmapdata, red.get(position).getScore());
				(new ExecuteNetworkOpp(new AddToHandRequestService(httpclient, this, addToHandRequest))).start();
				
				totalScore += red.get(position).getScore();
				handCardMap.put(red.get(position).getCardId(), red.get(position));
				openCardMap.remove(red.get(position).getCardId());
				
				hand.add(red.get(position));
				red.remove(position);
				
				galImageAdapter_red = new	GalleryAdapterAll(this, red, Constants.cardType.RED);
				gallery_open.setAdapter(galImageAdapter_red);

				if ((position - 1) > 0) {
					gallery_open.setSelection((position - 1), false);
				}else if(position == 0 && count > 1)
					gallery_open.setSelection((position), false);
				
				galImageAdapter_hand = new GalleryAdapterHand(this, hand);
				gallery_hand.setAdapter(galImageAdapter_hand);
				break;
				
			case BLUE:
				blue.get(position).setScore(blue.get(position).getCardStar().getValue()*scoreConstant);
				addToHandRequest = new AddToHandRequest(blue.get(position).getCardId(), userName, bitmapdata, blue.get(position).getScore());
				(new ExecuteNetworkOpp(new AddToHandRequestService(httpclient, this, addToHandRequest))).start();
				
				totalScore += blue.get(position).getScore();
				handCardMap.put(blue.get(position).getCardId(), blue.get(position));
				openCardMap.remove(blue.get(position).getCardId());
				
				hand.add(blue.get(position));
				blue.remove(position);
				
				galImageAdapter_blue = new	GalleryAdapterAll(this, blue, Constants.cardType.BLUE);
				gallery_open.setAdapter(galImageAdapter_blue);

				if ((position - 1) > 0) {
					gallery_open.setSelection((position - 1), false);
				}else if(position == 0 && count > 1)
					gallery_open.setSelection((position), false);
				
				galImageAdapter_hand = new GalleryAdapterHand(this, hand);
				gallery_hand.setAdapter(galImageAdapter_hand);
				break;
				
			case GREEN:
				green.get(position).setScore(green.get(position).getCardStar().getValue()*scoreConstant);
				addToHandRequest = new AddToHandRequest(green.get(position).getCardId(), userName, bitmapdata, green.get(position).getScore());
				(new ExecuteNetworkOpp(new AddToHandRequestService(httpclient, this, addToHandRequest))).start();
				
				totalScore += green.get(position).getScore();
				handCardMap.put(green.get(position).getCardId(), green.get(position));
				openCardMap.remove(green.get(position).getCardId());
				
				hand.add(green.get(position));
				green.remove(position);
				
				galImageAdapter_green = new	GalleryAdapterAll(this, green, Constants.cardType.GREEN);
				gallery_open.setAdapter(galImageAdapter_green);

				if ((position - 1) > 0) {
					gallery_open.setSelection((position - 1), false);
				}else if(position == 0 && count > 1)
					gallery_open.setSelection((position), false);
				
				galImageAdapter_hand = new GalleryAdapterHand(this, hand);
				gallery_hand.setAdapter(galImageAdapter_hand);
				break;
				
			case YELLOW:
				yellow.get(position).setScore(yellow.get(position).getCardStar().getValue()*scoreConstant);
				addToHandRequest = new AddToHandRequest(yellow.get(position).getCardId(), userName, bitmapdata, yellow.get(position).getScore());
				(new ExecuteNetworkOpp(new AddToHandRequestService(httpclient, this, addToHandRequest))).start();
				
				totalScore += yellow.get(position).getScore();
				handCardMap.put(yellow.get(position).getCardId(), yellow.get(position));
				openCardMap.remove(yellow.get(position).getCardId());
				
				hand.add(yellow.get(position));
				yellow.remove(position);
				
				galImageAdapter_yellow = new	GalleryAdapterAll(this, yellow, Constants.cardType.YELLOW);
				gallery_open.setAdapter(galImageAdapter_yellow);

				if ((position - 1) > 0) {
					gallery_open.setSelection((position - 1), false);
				}else if(position == 0 && count > 1)
					gallery_open.setSelection((position), false);
				
				galImageAdapter_hand = new GalleryAdapterHand(this, hand);
				gallery_hand.setAdapter(galImageAdapter_hand);
				break;
		}
		//((GalleryAdapterAll)gallery_open.getAdapter()).getCardType()
		//gallery_open.getSelectedItemPosition();
		
		// Setting the updated Score
		scoreView.setText(""+totalScore+"");
	}
	
	private Card generateCard(CardInfoContainer cardInfoContainer)
	{
		
		switch(cardInfoContainer.getCardId())
		{
		case RED_1:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.red_1), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case RED_2:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.red_2), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case RED_3:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.red_3), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case RED_4:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.red_4), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case RED_5:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.red_5), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case RED_6:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.red_6), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case RED_7:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.red_7), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
			
		case BLUE_1:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.blue_1), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case BLUE_2:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.blue_2), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case BLUE_3:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.blue_3), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case BLUE_4:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.blue_4), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case BLUE_5:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.blue_5), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case BLUE_6:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.blue_6), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case BLUE_7:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.blue_7), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
			
		case GREEN_1:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.green_1), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case GREEN_2:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.green_2), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case GREEN_3:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.green_3), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case GREEN_4:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.green_4), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case GREEN_5:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.green_5), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case GREEN_6:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.green_6), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case GREEN_7:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.green_7), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
			
		case YELLOW_1:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.yellow_1), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case YELLOW_2:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.yellow_2), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case YELLOW_3:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.yellow_3), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case YELLOW_4:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.yellow_4), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case YELLOW_5:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.yellow_5), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case YELLOW_6:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.yellow_6), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
		case YELLOW_7:
			return new Card(cardInfoContainer.getCardId(), getResources().getDrawable(R.drawable.yellow_7), cardInfoContainer.getCardStar(), cardInfoContainer.getCardScore());
			
		}
		return null;
	}
	
	private GalleryAdapterAll getGalleryAdapterAll(List<Card> cardList, Constants.cardType cardType)
	{
		return new GalleryAdapterAll(this, cardList, cardType);
	}
	
	private GalleryAdapterHand getGalleryAdapterHand(List<Card> cardList)
	{
		return new GalleryAdapterHand(this, cardList);
	}
	
	private class HandItemClickListener implements OnItemClickListener
	{

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view, int pos, long arg3) {
			// TODO Auto-generated method stub
			
			//int position = gallery_hand.getSelectedItemPosition();
			int position = pos;
			int innerVirtualPosition = hand.get(position).getCardId().getPosition();
			int innerRealPosition;
			int galleryOpenPosition;
			Card tmpCardHolder = null;
			DropCardRequest dropCardRequest = null;
			
			System.out.println("Hand Position --> "+position);
			
			switch(hand.get(position).getCardId().getCardType())
			{
				case RED:
					tmpCardHolder = hand.remove(position);
					
					if( ((GalleryAdapterAll)gallery_open.getAdapter()).getCardType() == Constants.cardType.RED )
					{
						galleryOpenPosition = gallery_open.getSelectedItemPosition();
						innerRealPosition = red.get(galleryOpenPosition).getCardId().getPosition();
						
						red.add(tmpCardHolder);
						Collections.sort(red, CARD_COMPARATOR);
						
						galImageAdapter_red = getGalleryAdapterAll(red, Constants.cardType.RED);
						gallery_open.setAdapter(galImageAdapter_red);
						
						if(innerRealPosition < innerVirtualPosition)
							gallery_open.setSelection((galleryOpenPosition), false);
						else
							gallery_open.setSelection((galleryOpenPosition+1), false);
					}else{
						red.add(tmpCardHolder);
						Collections.sort(red, CARD_COMPARATOR);
					}
					
					galImageAdapter_hand = getGalleryAdapterHand(hand);
					gallery_hand.setAdapter(galImageAdapter_hand);
					break;
					
				case BLUE:
					tmpCardHolder = hand.remove(position);
					
					if( ((GalleryAdapterAll)gallery_open.getAdapter()).getCardType() == Constants.cardType.BLUE )
					{
						galleryOpenPosition = gallery_open.getSelectedItemPosition();
						innerRealPosition = blue.get(galleryOpenPosition).getCardId().getPosition();
						
						blue.add(tmpCardHolder);
						Collections.sort(blue, CARD_COMPARATOR);
						
						galImageAdapter_blue = getGalleryAdapterAll(blue, Constants.cardType.BLUE);
						gallery_open.setAdapter(galImageAdapter_blue);
						
						if(innerRealPosition < innerVirtualPosition)
							gallery_open.setSelection((galleryOpenPosition), false);
						else
							gallery_open.setSelection((galleryOpenPosition+1), false);
					}else{
						blue.add(tmpCardHolder);
						Collections.sort(blue, CARD_COMPARATOR);
					}
					
					galImageAdapter_hand = getGalleryAdapterHand(hand);
					gallery_hand.setAdapter(galImageAdapter_hand);
					break;
					
				case GREEN:
					tmpCardHolder = hand.remove(position);
					
					if( ((GalleryAdapterAll)gallery_open.getAdapter()).getCardType() == Constants.cardType.GREEN )
					{
						galleryOpenPosition = gallery_open.getSelectedItemPosition();
						innerRealPosition = green.get(galleryOpenPosition).getCardId().getPosition();
						
						green.add(tmpCardHolder);
						Collections.sort(green, CARD_COMPARATOR);
						
						galImageAdapter_green = getGalleryAdapterAll(green, Constants.cardType.GREEN);
						gallery_open.setAdapter(galImageAdapter_green);
						
						if(innerRealPosition < innerVirtualPosition)
							gallery_open.setSelection((galleryOpenPosition), false);
						else
							gallery_open.setSelection((galleryOpenPosition+1), false);
					}else{
						green.add(tmpCardHolder);
						Collections.sort(green, CARD_COMPARATOR);
					}
					
					galImageAdapter_hand = getGalleryAdapterHand(hand);
					gallery_hand.setAdapter(galImageAdapter_hand);
					break;
					
				case YELLOW:
					tmpCardHolder = hand.remove(position);
					
					if( ((GalleryAdapterAll)gallery_open.getAdapter()).getCardType() == Constants.cardType.YELLOW )
					{
						galleryOpenPosition = gallery_open.getSelectedItemPosition();
						innerRealPosition = yellow.get(galleryOpenPosition).getCardId().getPosition();
						
						yellow.add(tmpCardHolder);
						Collections.sort(yellow, CARD_COMPARATOR);
						
						galImageAdapter_yellow = getGalleryAdapterAll(yellow, Constants.cardType.YELLOW);
						gallery_open.setAdapter(galImageAdapter_yellow);
						
						if(innerRealPosition < innerVirtualPosition)
							gallery_open.setSelection((galleryOpenPosition), false);
						else
							gallery_open.setSelection((galleryOpenPosition+1), false);
					}else{
						yellow.add(tmpCardHolder);
						Collections.sort(yellow, CARD_COMPARATOR);
					}
					
					galImageAdapter_hand = getGalleryAdapterHand(hand);
					gallery_hand.setAdapter(galImageAdapter_hand);
					break;
			}
			
			// *** DUMMY SERVER CALL ***
			if(tmpCardHolder != null)
			{
				dropCardRequest = new DropCardRequest(tmpCardHolder.getCardId(), userName);
				initDropCardThread(dropCardRequest);
				
				handCardMap.remove(tmpCardHolder.getCardId());
				openCardMap.put(tmpCardHolder.getCardId(), tmpCardHolder);
				
				totalScore -= tmpCardHolder.getScore();
				tmpCardHolder.setScore(0);
				
				// Setting the updated Score
				scoreView.setText(""+totalScore+"");
			}
			
		}
		
	}
	
	private void initDropCardThread(DropCardRequest dropCardRequest)
	{
		(new ExecuteNetworkOpp(new DropCardRequestService(httpclient, this, dropCardRequest))).start();
	}
	
	public void update(Update update)
	{
		if(handCardMap.containsKey(update.getCardId()))
		{
			handCardMap.get(update.getCardId()).setCardStar(update.getCardStar());
		}else if(openCardMap.containsKey(update.getCardId()))
		{
			openCardMap.get(update.getCardId()).setCardStar(update.getCardStar());
			
			if( ((GalleryAdapterAll)gallery_open.getAdapter()).getCardType() == update.getCardId().getCardType() )
			{
				switch(((GalleryAdapterAll)gallery_open.getAdapter()).getCardType())
				{
					case RED:
						setValueonRatingBar(red.get(gallery_open.getSelectedItemPosition()).getCardStar().getExp());
						break;
						
					case BLUE:
						setValueonRatingBar(blue.get(gallery_open.getSelectedItemPosition()).getCardStar().getExp());
						break;
						
					case GREEN:
						setValueonRatingBar(green.get(gallery_open.getSelectedItemPosition()).getCardStar().getExp());
						break;
						
					case YELLOW:
						setValueonRatingBar(yellow.get(gallery_open.getSelectedItemPosition()).getCardStar().getExp());
						break;
				}
			}
		}
	}
	
	private static Comparator<Card> CARD_COMPARATOR = new Comparator<Card>() 
	{
		@Override
		public int compare(Card card_1, Card card_2) 
		{
			// TODO Auto-generated method stub
			return card_1.getCardId().getPosition() - card_2.getCardId().getPosition();
		}
	};
	
	private class GameTimerTask extends TimerTask 
	{
	    public void run() 
	    {
	    	if(sec != 0)
	    		sec -= 1;
	    	else if(sec == 0 && minute != 0 )
	    	{
	    		minute -= 1;
	    		sec = 59;
	    	}else{
	    		timer.cancel();
	    		timerEnd = true;
	    	}
	    	
	    	GameActivity.this.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					if(timerEnd)
					{
						if(gameUpdateThread != null)
						{
							gameUpdateThread.setValidity(false);
						}
						
						Toast.makeText(GameActivity.this, "Game Over",Toast.LENGTH_SHORT).show();
			    		
			    		Intent intent = new Intent();
						intent.setClassName("com.example.android_app", "com.example.android_app.MainActivity");
						startActivity(intent);
					}
					timerView.setText(minute+":"+sec);
				}
			});
	    	
	    }
	}
	
	private class GameUpdate extends Thread
	{
		MQTTConnection mqttConnection;
		boolean validThread;
		GameActivity gameActivity;
		
		public GameUpdate (GameActivity gameActivity) throws NotFoundException, MqttException
		{
			validThread = true;
			this.gameActivity = gameActivity;
		}
		
		public void setValidity(boolean val)
		{
			this.validThread = val;
		}
		
		@Override
		public void run() 
		{
			// TODO Auto-generated method stub
			mqttConnection = new MQTTConnection(getResources().getString(R.string.host), userName, getResources().getString(R.string.data_open_line), gameActivity);
			while(validThread)
			{
				
			}
			mqttConnection.closeConnection();
		}
	}

}
		
	
